<?php


namespace app\controller\api;


use app\BaseController;
use app\models\order\OrderModel;
use app\models\shop\ShopModel;
use app\models\user\AdminRoleModel;
use app\models\user\AdminUserModel;
use app\models\user\UserAddressModel;
use app\models\user\UserLevelModel;
use app\models\user\UserModel;
use app\services\config\ConfigService;
use app\services\delivery\DeliveryService;
use app\services\area\RegionService;
use app\services\user\AdminUserService;
use app\services\user\DetailIntegralService;
use app\services\user\DetailMoneyService;
use app\services\utils\QrcodeService;

use app\services\utils\TokenService;
use app\validate\UserBankValidate;
use app\validate\UserValidate;
use http\Client\Curl\User;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Validate;
use function Symfony\Component\Translation\t;

use app\models\user\UserBank;
use app\validate\ShopValidate;
use app\models\goods\GoodsCartModel;
use app\services\user\DetailedGreenScoresService;

class UserController extends BaseController
{

    /**
     * 余额充值
     * @return \think\response\Json
     */
    public function rechargeBalance(){
        try {
            $amount = $this->request->param('amount');
            if(!$amount || $amount <= 0){
                throw new Exception('充值金额需要大于0的数值');
            }
            $order_sn = createRechargeOrderSn();
            Db::name('recharge_order')->insert([
                'user_id' => $this->request->userId,
                'order_sn' => $order_sn,
                'amount' => $amount,
                'is_pay' => 0,
                'create_time' => time(),
            ]);
            return $this->success(['order_sn' => $order_sn]);
        }catch (Exception $exception){
            return $this->error($exception->getMessage());
        }
    }



    public function setDefaultAddress()
    {
        try {
            $id = $this->request->param('id');
            UserAddressModel::where('user_id', $this->request->userId)->update(['is_default' => 0]);
            UserAddressModel::where(['id' => $id, 'user_id' => $this->request->userId])->update(['is_default' => 1]);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getMembershipRules()
    {
        $type = $this->request->param('type');
        if ($type == 1) {
            $rules = ConfigService::getConfigValue('membership_rules');
        } else {
            $rules = ConfigService::getConfigValue('privacy_policy');
        }
        return $this->success($rules);
    }

    public function signIn()
    {
        try {
            $res = Db::name('user_attendance_record')
                ->where('user_id', $this->request->userId)
                ->where('create_time', strtotime(date('Y-m-d')))
                ->find();
            if ($res) {
                throw new Exception('今日已经签过到了！');
            }
            Db::name('user_attendance_record')->insert([
                'user_id' => $this->request->userId,
                'create_time' => strtotime(date('Y-m-d')),
            ]);
//            UserModel::where('id', $this->request->userId)->inc('integral')->update();

            $integral = ConfigService::getConfigValue('sign_award');

            //$type = DetailIntegralService::SIGN_IN;
//            DetailIntegralService::create($this->request->userId,$type,$integral,'');

            $type = DetailedGreenScoresService::SIGN_IN;
            DetailedGreenScoresService::create($this->request->userId,$type,$integral,'');

            return $this->success('恭喜您，签到成功，积分加1');
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 注册
     */
    public function register()
    {
        Db::startTrans();
        try {
            $data = $this->request->only(['mobile', 'password', 'invite_code','secondary_password','code']);
            $validate = new UserValidate();
            $result = $validate->scene("register")->check($data);
            if (!$result) {
                throw new \Exception($validate->getError());
            }
            if($data['password'] !== $data['secondary_password']){
                throw new \Exception('两次密码不一致');
            }

            $userInfo = Db::name('user')->where('mobile', $data['mobile'])->find();
            if ($userInfo) {
                throw new \Exception('账号已存在');
            }

            // 邀请人
            $inviteCode = $data['invite_code'];
            if(!empty($inviteCode)){
                $inviteUserInfo = UserModel::where('invite_code', $inviteCode)->find();
                if (!$inviteUserInfo) {
                    throw new \Exception('邀请人不存在');
                }
                $data['invite_code'] = createUserCode();
                $data['inviter'] = $inviteUserInfo['id'];
            }
            $data['invite_code'] = createUserCode();
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT); //md5($data['password']);
            $data['create_time'] = time();
            $token = random(50, 'string');
            //$data['login_token'] = $token;
            $data['token'] = $token;
            unset($data['secondary_password']);
            unset($data['code']);
            $id = Db::name('user')->insertGetId($data);
            if (!$id) {
                throw new \Exception('注册失败');
            }
            $relation = empty($inviteCode) ? $id.'-' : $inviteUserInfo['relation'] . $id . '-';
            Db::name('user')->where('id', $id)->update([
                'relation' => $relation,
                'update_time' => time()
            ]);

            //邀请人赠送积分
            if(!empty($inviteCode)){
                $type = DetailedGreenScoresService::DIRECT_PUSH;
                $direct_push = ConfigService::getConfigValue('direct_push');

                DetailedGreenScoresService::create($inviteUserInfo['id'],$type,$direct_push);
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }


    public function getServiceIp()
    {
        $ip = [
            '192.168.137.1',
            '192.168.3.49'
        ];
        $this->success($ip);
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getUserInfo()
    {
        $userfield = 'id,avatar,nick,mobile,sex,level_id,status,label';
        $userInfo = UserModel::where('id', $this->request->userId)
            ->field($userfield)
            ->find()
            ->toArray();
        $status = ShopModel::where('user_id', $this->request->userId)->value('status');
        $userInfo['is_shop'] = $status ?? 0;
        $userInfo['level_preferential'] = UserLevelModel::where('id',$userInfo['level_id'])->value('preferential') ?? 0;
        $userInfo['level_name'] = UserLevelModel::where('id', $userInfo['level_id'])->value('name') ?? '';
        $userInfo['is_signIn'] = Db::name('user_attendance_record')->where(['user_id' => $this->request->userId, 'create_time' => strtotime(date('Y-m-d'))])->find() ? 1 : 0;

        //TODO 用户银行卡数量
        $userInfo['cart_num'] = GoodsCartModel::where('user_id', $this->request->userId)->count();
        $userInfo['bank_num'] = UserBank::where('user_id',$this->request->userId)->count();

        $orderWhere = [
            ['user_id','=',$this->request->userId],
            ['is_del','=',0],
        ];
        $pending_payment = OrderModel::where($orderWhere)->where('order_status',1)->where('is_del',0)->count();
        $to_be_shipped = OrderModel::where($orderWhere)->where('order_status',2)->where('is_del',0)->count();
        $to_be_received = OrderModel::where($orderWhere)->where('order_status',3)->where('is_del',0)->count();
        $completed = OrderModel::where($orderWhere)->where('order_status',5)->where('is_del',0)->count();
        $pendin_refund = OrderModel::where($orderWhere)->where('order_status','in',[7,8])->where('is_del',0)->count();
        $userInfo['order'] = [
            //'0已取消 1待付款 2待领取,待发货 3已发货,待收货 4已收货,待完成 5已完成 6已取消 7待售后 8已处理',
            'pending_payment' => $pending_payment, //待付款
            'to_be_shipped' => $to_be_shipped,  //待发货
            'to_be_received' => $to_be_received,    //待收货
            'completed' => $completed,  //完成
            'pendin_refund' => $pendin_refund,  //待退款
        ];
        //收藏数量
        $userInfo['collect'] = Db::name('goods_collect')->where('user_id',$this->request->userId)->count();

        $userInfo['authentication'] = Db::name('user_authentication')->where('user_id',$this->request->userId)->count();

        return $this->success($userInfo);
    }

    /**
     * 分享二维码
     * @return \think\response\Json
     */
    public function getUserQrcode()
    {
        try {
            $userId = $this->request->userId;
            $userInfo = UserModel::find($userId);

            if(empty($userInfo['invite_code'])){
                $userInfo['invite_code'] = createUserCode();
                $userInfo['qrcode'] = '';
            }

//            if($userInfo['qrcode']){
//                $qrcode = $userInfo['qrcode'];
//            }else{
//                $qrcode = QrcodeService::createUserQrcode($userInfo['invite_code'], $userId);
//                UserModel::where('id',$userId)->update(['qrcode' => $qrcode,'invite_code' => $userInfo['invite_code']]);
//            }
            //注册页二维码
            $register_url = ConfigService::getConfigValue('register_url');
            $qrcode = QrcodeService::createUserQrcode($register_url.'?invite_code='.$userInfo['invite_code'], $userId);

            $share_back = ConfigService::getConfigValue('share_back');

            return $this->success(['qrcode' => $qrcode, 'invite_code' => $userInfo['invite_code'],'share_back' => $share_back]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 退出登陆
     * @return \think\response\Json
     */
    public function loginOut()
    {
        try {
            $userId = $this->request->userId;
            Db::name('user')->where('id', $userId)->update(['token' => random(50, 'string')]);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getUser()
    {
        $userInfo = $this->request->userInfo;
        // 推广奖金
        $tuiGuangArr = Db::name('detailed_money')->where('type', 0)
            ->where('user_id', $userInfo['id'])
            ->column("money");
        $tuiGuangTotal = array_sum($tuiGuangArr);
        $tuiGuangCount = count($tuiGuangArr);
        // 提现明细
        $withDrawTotal = Db::name('detailed_money')->where('user_id', $userInfo['id'])->where('type', 1)->count();
        // 粉丝数量
        $userCount = Db::name('user')->where('inviter', $userInfo['id'])->count();

        $userInfo['referrer_total'] = $tuiGuangTotal;
        $userInfo['referrer_count'] = $tuiGuangCount;
        $userInfo['withdraw_total'] = $withDrawTotal;
        $userInfo['fans_count'] = $userCount;
        return $this->success($userInfo);
    }

    /**
     * 提现
     * @return \think\response\Json
     */
    public function withdraw()
    {
        Db::startTrans();
        try {
            $userId = $this->request->userId;
            $money = $this->request->param('money');
            $userInfo = Db::name('user')->where('id', $userId)->lock(true)->find();
            $withdraw_config = ConfigService::getConfigValue('withdraw_config');
            if ($money < $withdraw_config['min']) {
                throw new \Exception('最少提现金额'.$withdraw_config['min']);
            }
            if($userInfo['money'] < $money){
                throw new \Exception('账户余额不足');
            }
            $bank_id = $this->request->param('bank_id');
            $bank_info = Db::name('user_withdraw')->where('id',$bank_id)->where('user_id',$userId)->find();
            if (!$bank_info) {
                throw new \Exception('请选择提现银行卡');
            }
            $type = DetailMoneyService::WITHDRAW;
            $order_sn = createWithdrawOrderSn();
            DetailMoneyService::create($this->request->userId,$type,$money,$order_sn);
            $rate = bcmul($money,$withdraw_config['rate']/100,2);
            Db::name('user')->where('id', $userId)->inc("total_withdraw", $money)->update();
            Db::name('user_withdraw')->insert([
                'user_id' => $userId,
                'before' => $userInfo['money'],
                'amount' => $money,
                'after' => $userInfo['money'] - $money,
                'rate' => $rate,
                'fack_receive' => $money - $rate,
                'create_time' => time(),
                //'img' =>  $this->request->param('img'),
                'type' => 3,
                'status' => 0,
                'bank_id' => $bank_id
            ]);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function getWithdrawConfig(){
        $data = ConfigService::getConfigValue('withdraw_config');
        $user = UserModel::find($this->request->userId);
        return $this->success(['data' => $data,'money' => $user['money']]);
    }

    /**
     * 提现列表
     * @return \think\response\Json
     */
    public function getWithdrawList()
    {
        try {
            $userId = $this->request->userId;
            $where [] = ['user_id', '=', $userId];
            $type = $this->request->param('type', -1);
            if ($type >= 0) {
                $where [] = ['status', '=', $type];
            }
            $list = Db::name('withdraw')->where($where)->order('id', 'desc')->paginate(['list_rows' => $this->limit, 'page' => $this->page])->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }



    public function getMyShop(){
        $data = ShopModel::where('user_id',$this->request->userId)->field('id,shop_name,address')->find();
        return $this->success($data);
    }

    /**
     * 佣金明细
     * @return \think\response\Json
     */
    public function getCommissionList()
    {
        try {
            $userId = $this->request->userId;
            $page = $this->page;
            $limit = $this->limit;
            $list = Db::name('detailed_money')
                ->where('user_id', $userId)
                ->where('type', 0)
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 我的粉丝
     * @return \think\response\Json
     */
    public function getFansList()
    {
        try {
            $userId = $this->request->userId;
            $page = $this->page;
            $limit = $this->limit;
            $teamUserArr = Db::name('user')->where('relation', 'like', '%' . $userId . '%')->column('id');
            $teamCount = count($teamUserArr);
            $paymentCount = Db::name('user_payment')->whereIn('customer_id', $teamUserArr)->count();
            $todayUpdateCount = Db::name('user_payment')->whereIn('customer_id', $teamUserArr)
                ->where('update_time', '>=', date('Y-m-d 00:00:00'))
                ->count();
            $todayCreateCount = Db::name('user_payment')->whereIn('customer_id', $teamUserArr)
                ->where('create_time', '>=', date('Y-m-d 00:00:00'))
                ->count();
            $list = Db::name('user')
                ->where('inviter', $userId)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                // 今日记账
                $userArr = Db::name('user')->where('relation', 'like', '%' . $v['id'] . '%')->column('id');
                $todayAmount = Db::name('order')
                    ->where('user_id|buy_user_id', 'in', $userArr)
                    ->where('create_time', '>=', date('Y-m-d 00:00:00'))
                    ->sum('price');
                $v['today_amount'] = $todayAmount;
                $amount = Db::name('order')
                    ->where('user_id', $v['id'])
                    ->where('create_time', '>=', date('Y-m-d 00:00:00'))
                    ->sum('price');
                $v['amount'] = $amount;
            }
            return $this->success(['list' => $list, 'team_count' => $teamCount, 'pay_count' => $paymentCount, 'today_update' => $todayUpdateCount,
                'today_create_count' => $todayCreateCount]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取用户地址
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserAddress()
    {
        $userId = $this->request->userId;
        $id = $this->request->param('id');
        if ($id) {
            $addressInfo = Db::name('user_address')->find($id);
        } else {
            $addressInfo = Db::name('user_address')->where('user_id', $userId)->order('is_default', 'desc')->select();
        }
        return $this->success($addressInfo);
    }

    /**
     * 设置地址
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setUserAddress()
    {
        $userId = $this->request->userId;
        $data = $this->request->only(['id', 'username', 'mobile', 'address', 'house', 'is_default']);
        if (isset($data['id']) && $data['id']) {
            $data['full_address'] = $data['address'] . $data['house'];
            if ($data['is_default']) {
                Db::name('user_address')->where(['user_id' => $userId])->update(['is_default' => 0]);
            }
            Db::name('user_address')->where(['user_id' => $userId, 'id' => $data['id']])->update($data);
        } else {
            if ($data['is_default']) {
                Db::name('user_address')->where(['user_id' => $userId])->update(['is_default' => 0]);
            }
            $data['full_address'] = $data['address'] . $data['house'];
            $data['create_time'] = time();
            $data['user_id'] = $userId;
            Db::name('user_address')->insert($data);
        }

        return $this->success();
    }



    /**
     * 发送短信
     * @return \think\response\Json
     */
    public function sendSmsCode()
    {
        try {
            $mobile = $this->request->param('mobile');
            $key = 'sms:code:' . $mobile;
            $code = rand(111111, 999999);
            if (Cache::get($key)) {
                throw new \Exception('发送频繁，请稍后再试');
            }
            Cache::set($key, $code, 60);
            sendSms($mobile, $code);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取用户支付信息
     * @return array|mixed|Db|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserPaymentInfo()
    {
        $userId = $this->request->userId;
        $userNick = Db::name('user')->where('id', $userId)->value('nick_name');
        $paymentInfo = Db::name('user_payment')->where('customer_id', $userId)->find();
        $paymentInfo['user_nick'] = $userNick;
        return $this->success($paymentInfo);
    }


    public function getTeamList()
    {
        try {
            $userId = $this->request->userId;
            $type = $this->request->param('type');
            if ($type == 1) {
                // 直推用户列表
                $referrer = UserModel::where('inviter', $userId)
                    ->field('id,nick,mobile,total_cost,create_time')
                    ->select()
                    ->each(function ($item) {
                        $item['mobile'] = hideMobileMiddleFour($item['mobile']);
                        return $item;
                    })
                    ->toArray();
            } else {
                $ids = UserModel::where('inviter', $userId)->column('id');
                $referrer = UserModel::where('inviter', 'in', $ids)
                    ->field('id,nick,mobile,total_cost,create_time')
                    ->select()
                    ->each(function ($item) {
                        $item['mobile'] = hideMobileMiddleFour($item['mobile']);
                        return $item;
                    })
                    ->toArray();
            }


            return $this->success($referrer);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage() . $exception->getLine() . $exception->getFile());
        }
    }






    //提交认证信息
    public function submit_authentication()
    {
        try {
            $userId = $this->request->userId;

            $frontal_photo = $this->request->param('frontal_photo');
            if(empty($frontal_photo)){
                throw new Exception('请上传身份证正面照');
            }
            $backside_photo = $this->request->param('backside_photo');
            if(empty($backside_photo)){
                throw new Exception('请上传身份证反面照');
            }
            $document_type = $this->request->param('document_type');
            if(empty($document_type)){
                throw new Exception('请填写证件类型');
            }

            $name = $this->request->param('name');
            if(empty($backside_photo)){
                throw new Exception('请填写真实姓名');
            }
            $id_card = $this->request->param('id_card');
            if(empty($backside_photo)){
                throw new Exception('请填写证件号码');
            }
            $phone = $this->request->param('phone');
            if(empty($backside_photo)){
                throw new Exception('请填写手机号');
            }
            $data = [
                'user_id' => $userId,
                'document_type' => $document_type,
                'frontal_photo' => $frontal_photo,
                'backside_photo' => $backside_photo,
                'name' => $name,
                'id_card' =>  $id_card,
                'phone' => $phone
            ];

            $info = Db::name('user_authentication')->where('user_id',$userId)->find();
            if($info){
                if($info['status'] == 1){
                    throw new Exception('您的实名认证已通过');
                }
                if($info['status'] == 0){
                    throw new Exception('您的实名认证正在审核中');
                }
                $data['status'] = 1;
                $data['update_time'] = time();
                Db::name('user_authentication')->where('id',$info['id'])->update($data);
            }else{
                $data['status'] = 0;
                $data['create_time'] = time();
                Db::name('user_authentication')->insert($data);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 登陆
     * @return \think\response\Json
     */
    public function login()
    {
        Db::startTrans();
        try {
            $data = $this->request->only(['mobile', 'password']);
            $validate = new UserValidate();
            $result = $validate->scene("login")->check($data);
            if (!$result) {
                throw new \Exception($validate->getError());
            }
            $userInfo = Db::name('user')->where('mobile', $data['mobile'])->find();
            if (!$userInfo) {
                throw new \Exception('账号错误');
            }
            if (!password_verify($data['password'], $userInfo['password'])) {
                throw new \Exception('密码错误');
            }
            $token = random(30, 'all');
            $info = [];
            $info['last_login_time'] = time();
            $info['last_login_ip'] = $this->request->ip();
            $info['update_time'] = time();
            $info['token'] = $token;
            $info['valid_time'] = time() + 86400;

            Db::name('user')->where('id', $userInfo['id'])->update($info);
            unset($userInfo['password']);
            $userInfo['token'] = $token;
            Db::commit();
            return $this->success($userInfo);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 修改密码, 修改登录密码
     * @return \think\response\Json
     */
    public function modifyPwd()
    {
        try {
//            $mobile = $this->request->param('mobile');
//            $password = $this->request->param('password');
//            $code = $this->request->param('code');
//            if (!verifySmsCode($mobile, $code)) {
//                throw new \Exception('验证码错误');
//            }
//            if (!$password || (strlen($password) < 6 && strlen($password) > 16)) {
//                throw new \Exception('密码长度在6-16位之间');
//            }

            $userid = $this->request->userId;
            $old_password = $this->request->param('old_password');
            $password = $this->request->param('password');
            $confirm_password = $this->request->param('confirm_password');
            if($password !== $confirm_password){
                throw new \Exception('两次密码不一致');
            }
            if (!$password || (strlen($password) < 6 && strlen($password) > 16)) {
                throw new \Exception('密码长度在6-16位之间');
            }

            $userInfo = Db::name('user')->where('id', $userid)->find();
            if (!$userInfo) {
                throw new \Exception('用户不存在');
            }
            if (!password_verify($old_password, $userInfo['password'])) {
                throw new \Exception('旧密码输入错误');
            }
            $list = Db::name('user')
                ->where('id', $userid)
                ->update([
                    'password' => password_hash($password, PASSWORD_DEFAULT),
                    'update_time' => time()
                ]);
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 设置用户信息
     * @return \think\response\Json
     */
    public function setUserInfo()
    {
        Db::startTrans();
        try {
            $userId = $this->request->userId;
            $userNick = $this->request->param('nick', '', 'trim');
            $userNick = htmlspecialchars($userNick, ENT_QUOTES, 'UTF-8');
            $avatar = $this->request->param('avatar');
            $mobile = $this->request->param('mobile');
            $sex = $this->request->param('sex');
            $user = UserModel::find($userId);
            $user->mobile = $mobile;
            $user->avatar = $avatar;
            $user->nick = $userNick;
            $user->sex = $sex;
            $user->save();
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 修改支付
     * @return \think\response\Json
     */
    public function modifyPaymentPwd()
    {
        try {
            $userid = $this->request->userId;
            $old_password = $this->request->param('old_password');
            $password = $this->request->param('password');
            $confirm_password = $this->request->param('confirm_password');
            if($password !== $confirm_password){
                throw new \Exception('两次密码不一致');
            }
            if(empty($password)){
                throw new \Exception('密码不能为空');
            }
//            if (!$password || (strlen($password) < 6 && strlen($password) > 16)) {
//                throw new \Exception('密码长度在6-16位之间');
//            }

            $userInfo = Db::name('user')->where('id', $userid)->find();
            if (!$userInfo) {
                throw new \Exception('用户不存在');
            }
            if(!empty($userInfo['payment_password'])){
                if (!password_verify($old_password, $userInfo['payment_password'])) {
                    throw new \Exception('旧密码输入错误');
                }
            }
            $list = Db::name('user')
                ->where('id', $userid)
                ->update([
                    'payment_password' => md5($password),
                    'update_time' => time()
                ]);
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 银行卡列表
     * @return \think\response\Json
     */
    public function getBankList()
    {
        try{
            $user_id = $this->request->userId;

            $field = 'id,name,bank_card_no,accounts_bank';
            $list = UserBank::where('user_id',$user_id)->field($field)->select();

            foreach($list as $key => $item){
                //银行卡号脱敏
                $length = strlen($item['bank_card_no']);
                $item['bank_card_no'] = ($length <= 4) ? $item['bank_card_no'] : substr($item['bank_card_no'], $length - 4);
            }

            return $this->success($list);
        }catch (\Exception $exception){
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 添加银行卡
     * @return \think\response\Json
     */
    public function setBank()
    {
        try {
            $userid = $this->request->userId;

            $data = $this->request->only([
                'frontal_photo',
                'backside_photo',
                'name',
                'id_card',
                'validity_period',
                'start_validity_period',
                'end_validity_period',
                'cell_phone',
                'bank_card_no',
                'accounts_bank',
                'bank_address',
                'bank_sub_branch',
                'reserved_number',
                'account_type',
            ]);

            Validate(UserBankValidate::class)->check($data);

            if($data['validity_period'] == 2){
                if(empty($data['start_validity_period']) || empty($data['end_validity_period'])){
                    throw new \Exception('请输入证件有效期');
                }
            }

            $data['user_id'] = $userid;
            $data['create_time'] = time();
            $data['update_time'] = time();

            $info = UserBank::where('user_id',$userid)->where('bank_card_no',$data['bank_card_no'])->find();
            if($info){
                throw new \Exception('当前卡号已经绑定过了');
            }

            UserBank::create($data);

            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 入住商家提交
     * @return \think\response\Json
     */
    public function applyShop(){
        Db::startTrans();
        try {
            //门店名称、负责人姓名、负责人电话、地址、营业执照、商家logo、法人身份证照面照、法人身份证反面照
            $param = $this->request->param(['shop_name','username','mobile','address','business_img','logo','frontal_photo','backside_photo']);

            Validate(ShopValidate::class)->check($param);

            $shop = ShopModel::where('user_id',$this->request->user_id)->find();
            if($shop){
                if($shop['status'] == 0){
                    throw new \Exception('您的店铺正在审核中,请勿重复提交');
                }
            }
            $param['user_id'] = $this->request->userId;
            $param['status'] = 0;
            $shop = ShopModel::create($param);
            UserModel::where('id',$this->request->userId)->update(['shop_id' => $shop->id]);
            Db::commit();
            return $this->success();
        }catch (\Exception $exception){
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 余额明细
     * @return \think\response\Json
     */
    public function balanceRecord()
    {
        try {
            $userId = $this->request->userId;
            $where = [];
            $where[] = ['user_id', '=', $userId];

            $start_time = $this->request->param('start_time');
            //$end_time = $this->request->param('end_time');
            $type = $this->request->param('type','all');

            if(empty($start_time)){
                $start_time = strtotime(date('Y-m-01 00:00:00'));
                $end_time  = strtotime(date('Y-m-t 23:59:59'));

                $title = date('Y-m').'月';
                $where[] = ['create_time','between',[$start_time,$end_time]];
            }else{
                $title = $start_time;
                $start_time = strtotime($start_time);
                $end_time  = strtotime(date("Y-m-t 23:59:59", strtotime($start_time.'-01')));
            }
            $where[] = ['create_time','between',[$start_time,$end_time]];

            $total_revenue = Db::name('detailed_money')
                ->where($where)
                ->where('type','<',100)
                ->sum('amount'); //总收入
            $total_expenditure = Db::name('detailed_money')->where($where)->where('type','>',100)->sum('amount'); //总支出


            if($type != 'all'){
                if($type == 101){
                    $where[] = ['type','>',100];   //扣除
                }else{
                    $where[] = ['type','<',100];   //收入
                }
            }

            $list = Db::name('detailed_money')
                ->where($where)
                ->field('id,amount,remark,create_time,type')
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])->toArray();

            foreach ($list['data'] as &$v) {
                $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }


            $money = UserModel::where('id', $this->request->userId)->value('money');
            return $this->success([
                'data' => $list,
                'money' => $money,
                'title' => $title,
                'total_revenue' => $total_revenue,
                'total_expenditure' => $total_expenditure,
                'user_id' => $userId
            ]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 积分明细
     * @return \think\response\Json
     */
    public function integralRecord()
    {
        try {

            $userId = $this->request->userId;
            $where = [];
            $where[] = ['user_id', '=', $userId];

            $start_time = $this->request->param('start_time');
            $end_time = $this->request->param('end_time');
            $type = $this->request->param('type','all');

            if(empty($start_time)){
                $start_time = strtotime(date('Y-m-01 00:00:00'));
                $end_time  = strtotime(date('Y-m-t 23:59:59'));

                $title = date('Y-m').'月';
                $where[] = ['create_time','between',[$start_time,$end_time]];
            }else{
                $title = $start_time;
                $start_time = strtotime($start_time);
                $end_time  = strtotime(date("Y-m-t 23:59:59", strtotime($start_time.'-01')));
            }

            $where[] = ['create_time','between',[$start_time,$end_time]];

            $total_revenue = Db::name('detailed_integral')->where($where)->where('type','<',100)->sum('amount'); //总收入
            $total_expenditure = Db::name('detailed_integral')->where($where)->where('type','>',100)->sum('amount'); //总支出


            if($type != 'all'){
                if($type == 101){
                    $where[] = ['type','>',100];   //扣除
                }else{
                    $where[] = ['type','<',100];   //收入
                }
            }

            $list = Db::name('detailed_integral')
                ->where($where)
                ->field('id,amount,remark,create_time,type')
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])->toArray();

            foreach ($list['data'] as &$v) {
                $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }

            $money = UserModel::where('id', $this->request->userId)->value('integral');
            return $this->success([
                'data' => $list,
                'integral' => $money,
                'title' => $title,
                'total_revenue' => $total_revenue,
                'total_expenditure' => $total_expenditure
            ]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }



    /**
     * 绿色积分明细
     * @return \think\response\Json
     */
    public function greenScoresRecord()
    {
        try {
            $userId = $this->request->userId;
            $where = [];
            $where[] = ['user_id', '=', $userId];

            $start_time = $this->request->param('start_time');
            $end_time = $this->request->param('end_time');
            $type = $this->request->param('type','all');

            if(empty($start_time)){
                $start_time = strtotime(date('Y-m-01 00:00:00'));
                $end_time  = strtotime(date('Y-m-t 23:59:59'));

                $title = date('Y-m').'月';
                $where[] = ['create_time','between',[$start_time,$end_time]];
            }else{
                $title = $start_time;
                $start_time = strtotime($start_time);
                $end_time  = strtotime(date("Y-m-t 23:59:59", strtotime($start_time.'-01')));
            }
            $where[] = ['create_time','between',[$start_time,$end_time]];

            $total_revenue = Db::name('detailed_green_scores')->where($where)->where('type','<',100)->sum('amount'); //总收入
            $total_expenditure = Db::name('detailed_green_scores')->where($where)->where('type','>',100)->sum('amount'); //总支出


            if($type != 'all'){
                if($type == 101){
                    $where[] = ['type','>',100];   //扣除
                }else{
                    $where[] = ['type','<',100];   //收入
                }
            }

            $list = Db::name('detailed_green_scores')
                ->where($where)
                ->field('id,amount,remark,create_time,type')
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])->toArray();

            foreach ($list['data'] as &$v) {
                $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }

            $money = UserModel::where('id', $this->request->userId)->value('green_scores');
            return $this->success([
                'data' => $list,
                'green_scores' => $money,
                'title' => $title,
                'total_revenue' => $total_revenue,
                'total_expenditure' => $total_expenditure
            ]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    /**
     *
     * @return void
     */
    public function wallet()
    {
        try {
            $userId = $this->request->userId;

            $userfield = 'money,green_scores,integral';
            $userinfo = UserModel::where('id', $this->request->userId)->field($userfield)->find();

            $shop = ShopModel::where('user_id',$userId)->find();//->where('status',1)->find();

            return $this->success([
                'userinfo' => $userinfo,
                'is_shop' => empty($shop) ? 2 : 1,
                'shop_money' => empty($shop) ? "0" : $shop['money']
            ]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


}